#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QTimer>
#include <QMessageBox>
#include <QSerialPort>
#include <baudratedialog.h>

enum DeviceState {
    Stopped = 0,
    Running = 1,
};

enum SaveFormat {
    CSVFormat = 0,
    BINFormat = 1,
};

static const quint8 DEFAULT_CH_CNT = 4;
static const bool DEBUG = true;

static const bool DEFAULT_50K_SAMPLE = false;

QT_BEGIN_NAMESPACE
namespace Ui {
class MainWindow;
}
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

private slots:
    void startBtnClicked();
    void stopBtnClicked();
    void abnormalStop();
    void saveDataCheckBoxChecked();
    void chooseDirectoryBtnClicked();

    void processData();
    void mousePress();
    void mouseWheel();
    void selectionChanged();

    void displayAllSerialPortInfo();
    void displayHexAndDecodeFloats(const char *buf, qint64 size);
    void on_baudRate_currentTextChanged(const QString &arg1);
    void on_portNames_currentTextChanged(const QString &arg1);

private:
    void updateUI();
    void updateSerialPortSettings();
    void updateSaveWidgets();

    void setupUI();
    void setupRawData();
    void setupSumData();
    void setupFourQuad();
    void connectSlots();
    SaveFormat saveFormat();

    void saveData(const QString& filename, const QVector<double> &data, SaveFormat format);
    void saveDataCSV(const QString& filename, const QVector<double> &data);
    void saveDataBIN(const QString& filename, const QVector<double> &data);

protected:
    void closeEvent(QCloseEvent* e) override {
        QMessageBox::information(this, "提醒", "现在要退出四象限光斑处理软件?");
        QMainWindow::closeEvent(e);
        if(DeviceState::Running == deviceState) {
        }
    }

private:
    Ui::MainWindow *ui;

    bool initialized;


    QSerialPort *serialPort;
    DeviceState deviceState;
    int baudRate = 2000000;
    uint32_t initialRangeSize = 2000;
    QVector<double> sums;
    QVector<double> xdiffs;
    QVector<double> ydiffs;
    QVector<QVector<double>> receive_data;

    bool magicSkipped;

    bool shouldSaveData;
    QString saveDataPathPrefix;
    quint64 dataPointsCnt;

    BaudRateDialog *dialog;
};
#endif // MAINWINDOW_H
